package io.renren.modules.sys.service.impl;

import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;

import io.renren.common.constant.Code;
import io.renren.common.exception.BizException;
import io.renren.common.utils.ShiroUtils;
import io.renren.modules.sys.dao.DicGroupDetailDao;
import io.renren.modules.sys.entity.DicGroupDetail;
import io.renren.modules.sys.service.DicGroupDetailService;


@Service("dicGroupDetailService")
public class DicGroupDetailServiceImpl extends ServiceImpl<DicGroupDetailDao, DicGroupDetail> implements DicGroupDetailService {

	@Override
	public List<DicGroupDetail> selectPage(Map<String, Object> param) {
		if(param.get("page") != null && param.get("limit") != null){
			PageHelper.startPage(Integer.parseInt((String)param.get("page")), Integer.parseInt((String)param.get("limit")));
		}
		List<DicGroupDetail> lists = this.selectList(new EntityWrapper<DicGroupDetail>().
    			eq(StringUtils.isNotBlank((String)param.get("dicGpId")), "dic_gp_id", (String)param.get("dicGpId"))
    			.like(StringUtils.isNotBlank((String)param.get("name")),"name" ,(String)param.get("name"))
    			.orderBy("show_order"));
		
		return lists;
	}

	@Override
	@Transactional
	public DicGroupDetail saveDicGroupDetail(DicGroupDetail dicGroupDetail) {
		
		if(StringUtils.isEmpty(dicGroupDetail.getDicGpId())||StringUtils.isEmpty(dicGroupDetail.getName())
				||StringUtils.isEmpty(dicGroupDetail.getCode())) {
			throw new BizException(Code.COODE_SYS_O1,"名称、编码不能为空");
		}
		
		//校验重复
		DicGroupDetail detail = this.selectOne(new EntityWrapper<DicGroupDetail>().eq("dic_gp_id", dicGroupDetail.getDicGpId()).and("code = {0}", dicGroupDetail.getCode()));
		if(detail != null) {
			throw new BizException(Code.COODE_SYS_O2,"已存在相同编码的数据");
		}
		dicGroupDetail.setCreater(ShiroUtils.getUserEntity().getUsername());
		dicGroupDetail.setCreateUserId(ShiroUtils.getUserEntity().getUserId());
		dicGroupDetail.setTenantId(ShiroUtils.getUserEntity().getTenantId());
		dicGroupDetail.setCreateTime(System.currentTimeMillis());
		this.insert(dicGroupDetail);
		return dicGroupDetail;
	}
	
	

  
}
